package com.sardine.base.http;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HostParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class HttpCallUtils {

	public static final Logger logger = LoggerFactory.getLogger(HttpCallUtils.class);

	private static HttpClient httpClient;

	static {
		httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(2000); //连接2秒超时
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(2000);//读取2秒超时
		//连接一个host的默认最大连接数
		httpClient.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(100);
		//总的最大连接数
		httpClient.getHttpConnectionManager().getParams().setMaxTotalConnections(500);
	}


	public static String callPost(String url, Map<String, String> param,Long orderId)throws Exception {
		PostMethod method = new PostMethod(url);
		if (MapUtils.isNotEmpty(param)) {
			NameValuePair[] nameValueParam = new NameValuePair[param.size()];
			int count = 0;
			for (Entry<String, String> paramEntry : param.entrySet()) {
				NameValuePair nameValuePair = new NameValuePair(paramEntry.getKey(), paramEntry.getValue());
				nameValueParam[count++] = nameValuePair;
			}
//			参数放在body中
			method.setRequestBody(nameValueParam);
		}
		try {
            method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            int code = httpClient.executeMethod(method);
			String responseBodyString = "";
			if (200 == code){
				responseBodyString = method.getResponseBodyAsString();
			}else {
				logger.error("order:{},HttpCallUtils,code:{},responseBody:{}", new Object[]{orderId, code, method.getResponseBodyAsString()});
				throw new RuntimeException("HttpState="+code+",HttpState != 200");
			}
			logger.info("order:{},HttpCallUtils,code:{},responseBody:{}",new Object[]{orderId,code, JSON.toJSONString(responseBodyString)});
			return responseBodyString;
		} catch (Throwable t) {
			logger.error(orderId+"HttpCallUtils，post url:" + url, t);
			throw new RuntimeException(url,t);
		}finally {
			method.releaseConnection();
		}
	}


	public static String callPostHeader(String url, Map<String, Object> param,Long orderId,Map<String,String> header)throws Exception {
		PostMethod method = new PostMethod(url);
		if (MapUtils.isNotEmpty(param)) {
			List<NameValuePair> list=new ArrayList<>();
			for (Entry<String, Object> paramEntry : param.entrySet()) {
				if(paramEntry.getValue()!=null){
					NameValuePair nameValuePair = new NameValuePair(paramEntry.getKey(), paramEntry.getValue().toString());
					list.add(nameValuePair);
				}
			}
//			参数放在body中
			method.setRequestBody(list.toArray(new NameValuePair[list.size()] ));
		}
		try {
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			List<Header> headers = new ArrayList<Header>();
			if(!CollectionUtils.isEmpty(header)){
				for (Entry<String, String> entry : header.entrySet()) {
					headers.add(new Header(entry.getKey(),entry.getValue()));
				}
			}
			if(headers.size()>0){
				httpClient.getHostConfiguration().getParams().setParameter(HostParams.DEFAULT_HEADERS, headers);
			}
			int code = httpClient.executeMethod(method);
			String responseBodyString = "";
			if (200 == code){
				responseBodyString = method.getResponseBodyAsString();
			}else {
				logger.error("order:{},HttpCallUtils,code:{},responseBody:{}", new Object[]{orderId, code, method.getResponseBodyAsString()});
				throw new RuntimeException("HttpState="+code+",HttpState != 200");
			}
			logger.info("order:{},HttpCallUtils,code:{},responseBody:{}",new Object[]{orderId,code, JSON.toJSONString(responseBodyString)});
			return responseBodyString;
		} catch (Throwable t) {
			logger.error(orderId+"HttpCallUtils，post url:" + url, t);
			throw new RuntimeException(url,t);
		}finally {
			method.releaseConnection();
		}
	}

    public static String callPostRaw(String url, Map<String, Object> param,Long orderId)throws Exception {

        PostMethod method = new PostMethod(url);
        if (MapUtils.isNotEmpty(param)) {
            String json= JSON.toJSONString(param);
            StringRequestEntity re=new StringRequestEntity(json,"text/plain","UTF-8");
            //参数放在body中
            method.setRequestEntity(re);
        }
        try {
            method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            int code = httpClient.executeMethod(method);
            String responseBodyString = "";
            if (200 == code){
                responseBodyString = method.getResponseBodyAsString();
            }else {
                logger.error("order:{},HttpCallUtils,code:{},responseBody:{}", new Object[]{orderId, code, method.getResponseBodyAsString()});
                throw new RuntimeException("HttpState="+code+",HttpState != 200");
            }
            logger.info("order:{},HttpCallUtils,code:{},responseBody:{}",new Object[]{orderId,code, JSON.toJSONString(responseBodyString)});
            return responseBodyString;
        } catch (Throwable t) {
            logger.error(orderId+"HttpCallUtils，post url:" + url, t);
            throw new RuntimeException(url,t);
        }finally {
            method.releaseConnection();
        }
    }


}
